package swing;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;

import modele.Formation;
import modele.Theme;
import dao.FormationDAO;
import dao.FormationThemeDAO;
import dao.ThemeDAO;

public class FormationPanel extends JPanel {

	private static final long		serialVersionUID	= 1L;

	private FormationListePanel		formationListePanel;
	private int						edtFormationId;

	private DefaultListModel<Theme>	themeListModel;
	private JList<Theme>			themeList;

	private JTextField				textTitre;
	private JTextField				textCertification;
	private JTextField				textPrerequis;
	private JTextField				textCode;
	private JTextField				textIdFormation;
	private JButton					btnSauvegarder;
	private JButton					btnReinitialiser;
	private JScrollPane				themesScrollPanel;
	private JTextArea				textContenu;
	private JTextArea				textObjectif;

	public FormationPanel() {

		setBorder(new EmptyBorder(10, 10, 10, 10));
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[] { 0, 0, 0, 0 };
		gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
		gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 1.0, Double.MIN_VALUE };
		gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, Double.MIN_VALUE };
		setLayout(gridBagLayout);

		JLabel labelId = new JLabel("Id");
		GridBagConstraints gbc_labelId = new GridBagConstraints();
		gbc_labelId.anchor = GridBagConstraints.EAST;
		gbc_labelId.insets = new Insets(0, 0, 5, 5);
		gbc_labelId.gridx = 1;
		gbc_labelId.gridy = 0;
		add(labelId, gbc_labelId);

		textIdFormation = new JTextField();
		textIdFormation.setBorder(new EmptyBorder(5, 5, 5, 5));
		textIdFormation.setEnabled(false);
		GridBagConstraints gbc_textId1 = new GridBagConstraints();
		gbc_textId1.insets = new Insets(0, 0, 5, 0);
		gbc_textId1.fill = GridBagConstraints.HORIZONTAL;
		gbc_textId1.gridx = 2;
		gbc_textId1.gridy = 0;
		add(textIdFormation, gbc_textId1);
		textIdFormation.setColumns(10);

		JLabel labelTitre = new JLabel("Titre");
		GridBagConstraints gbc_labelTitre = new GridBagConstraints();
		gbc_labelTitre.anchor = GridBagConstraints.NORTHEAST;
		gbc_labelTitre.insets = new Insets(0, 0, 5, 5);
		gbc_labelTitre.gridx = 1;
		gbc_labelTitre.gridy = 1;
		add(labelTitre, gbc_labelTitre);

		textTitre = new JTextField();
		textTitre.setBorder(new EmptyBorder(5, 5, 5, 5));
		GridBagConstraints gbc_textTitre1 = new GridBagConstraints();
		gbc_textTitre1.insets = new Insets(0, 0, 5, 0);
		gbc_textTitre1.fill = GridBagConstraints.HORIZONTAL;
		gbc_textTitre1.gridx = 2;
		gbc_textTitre1.gridy = 1;
		add(textTitre, gbc_textTitre1);
		textTitre.setColumns(10);
		textTitre.setHorizontalAlignment(JTextField.LEFT);

		JLabel labelCode = new JLabel("Code");
		GridBagConstraints gbc_labelCode = new GridBagConstraints();
		gbc_labelCode.anchor = GridBagConstraints.EAST;
		gbc_labelCode.insets = new Insets(0, 0, 5, 5);
		gbc_labelCode.gridx = 1;
		gbc_labelCode.gridy = 2;
		add(labelCode, gbc_labelCode);

		textCode = new JTextField();
		textCode.setBorder(new EmptyBorder(5, 5, 5, 5));
		GridBagConstraints gbc_textCode1 = new GridBagConstraints();
		gbc_textCode1.insets = new Insets(0, 0, 5, 0);
		gbc_textCode1.fill = GridBagConstraints.HORIZONTAL;
		gbc_textCode1.gridx = 2;
		gbc_textCode1.gridy = 2;
		add(textCode, gbc_textCode1);
		textCode.setColumns(10);

		JLabel labelCertification = new JLabel("Certification");
		GridBagConstraints gbc_labelCertification = new GridBagConstraints();
		gbc_labelCertification.anchor = GridBagConstraints.NORTHEAST;
		gbc_labelCertification.insets = new Insets(0, 0, 5, 5);
		gbc_labelCertification.gridx = 1;
		gbc_labelCertification.gridy = 3;
		add(labelCertification, gbc_labelCertification);

		textCertification = new JTextField();
		textCertification.setBorder(new EmptyBorder(5, 5, 5, 5));
		GridBagConstraints gbc_textCertification1 = new GridBagConstraints();
		gbc_textCertification1.insets = new Insets(0, 0, 5, 0);
		gbc_textCertification1.fill = GridBagConstraints.HORIZONTAL;
		gbc_textCertification1.gridx = 2;
		gbc_textCertification1.gridy = 3;
		add(textCertification, gbc_textCertification1);
		textCertification.setColumns(10);

		JLabel labelPrerequis = new JLabel("Pre-requis");
		GridBagConstraints gbc_labelPrerequis = new GridBagConstraints();
		gbc_labelPrerequis.anchor = GridBagConstraints.EAST;
		gbc_labelPrerequis.insets = new Insets(0, 0, 5, 5);
		gbc_labelPrerequis.gridx = 1;
		gbc_labelPrerequis.gridy = 4;
		add(labelPrerequis, gbc_labelPrerequis);

		textPrerequis = new JTextField();
		textPrerequis.setBorder(new EmptyBorder(5, 5, 5, 5));
		GridBagConstraints gbc_textPrerequis1 = new GridBagConstraints();
		gbc_textPrerequis1.insets = new Insets(0, 0, 5, 0);
		gbc_textPrerequis1.fill = GridBagConstraints.HORIZONTAL;
		gbc_textPrerequis1.gridx = 2;
		gbc_textPrerequis1.gridy = 4;
		add(textPrerequis, gbc_textPrerequis1);
		textPrerequis.setColumns(10);

		JLabel labelThemes = new JLabel("Themes");
		GridBagConstraints gbc_labelThemes = new GridBagConstraints();
		gbc_labelThemes.anchor = GridBagConstraints.NORTHEAST;
		gbc_labelThemes.insets = new Insets(0, 0, 5, 5);
		gbc_labelThemes.gridx = 1;
		gbc_labelThemes.gridy = 5;
		add(labelThemes, gbc_labelThemes);

		themesScrollPanel = new JScrollPane();
		themesScrollPanel.setMinimumSize(new Dimension(22, 100));
		GridBagConstraints gbc_themesScrollPane1 = new GridBagConstraints();
		gbc_themesScrollPane1.insets = new Insets(0, 0, 5, 0);
		gbc_themesScrollPane1.fill = GridBagConstraints.BOTH;
		gbc_themesScrollPane1.gridx = 2;
		gbc_themesScrollPane1.gridy = 5;
		add(themesScrollPanel, gbc_themesScrollPane1);

		JLabel labelObjectif = new JLabel("Objectif");
		GridBagConstraints gbc_labelObjectif = new GridBagConstraints();
		gbc_labelObjectif.anchor = GridBagConstraints.NORTHEAST;
		gbc_labelObjectif.insets = new Insets(0, 0, 5, 5);
		gbc_labelObjectif.gridx = 1;
		gbc_labelObjectif.gridy = 6;
		add(labelObjectif, gbc_labelObjectif);

		JScrollPane objectifScrollPane = new JScrollPane();
		objectifScrollPane.setMinimumSize(new Dimension(22, 100));
		GridBagConstraints gbc_objectifScrollPane = new GridBagConstraints();
		gbc_objectifScrollPane.insets = new Insets(0, 0, 5, 0);
		gbc_objectifScrollPane.fill = GridBagConstraints.BOTH;
		gbc_objectifScrollPane.gridx = 2;
		gbc_objectifScrollPane.gridy = 6;
		add(objectifScrollPane, gbc_objectifScrollPane);

		textObjectif = new JTextArea();
		textObjectif.setMinimumSize(new Dimension(0, 50));
		textObjectif.setBorder(new EmptyBorder(5, 5, 5, 5));
		textObjectif.setWrapStyleWord(true);
		textObjectif.setLineWrap(true);
		objectifScrollPane.setViewportView(textObjectif);

		JLabel labelContenu = new JLabel("Contenu");
		GridBagConstraints gbc_labelContenu = new GridBagConstraints();
		gbc_labelContenu.anchor = GridBagConstraints.NORTHEAST;
		gbc_labelContenu.insets = new Insets(0, 0, 5, 5);
		gbc_labelContenu.gridx = 1;
		gbc_labelContenu.gridy = 7;
		add(labelContenu, gbc_labelContenu);

		JScrollPane contenuScrollPane = new JScrollPane();
		contenuScrollPane.setMinimumSize(new Dimension(22, 100));
		GridBagConstraints gbc_contenuScrollPane = new GridBagConstraints();
		gbc_contenuScrollPane.insets = new Insets(0, 0, 5, 0);
		gbc_contenuScrollPane.fill = GridBagConstraints.BOTH;
		gbc_contenuScrollPane.gridx = 2;
		gbc_contenuScrollPane.gridy = 7;
		add(contenuScrollPane, gbc_contenuScrollPane);

		textContenu = new JTextArea();
		textContenu.setMinimumSize(new Dimension(0, 50));
		textContenu.setWrapStyleWord(true);
		textContenu.setBorder(new EmptyBorder(5, 5, 5, 5));
		textContenu.setLineWrap(true);

		contenuScrollPane.setViewportView(textContenu);

		JPanel panel = new JPanel();
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(0, 0, 5, 0);
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 2;
		gbc_panel.gridy = 8;
		add(panel, gbc_panel);

		btnSauvegarder = new JButton("Sauvegarder");
		panel.add(btnSauvegarder);

		btnReinitialiser = new JButton("Reinitialiser");
		panel.add(btnReinitialiser);

		setThemeList();
		setBtnActions();
		setScrollLock();

	}

	/**
	 * Met le defilement au debut du texte
	 */
	public void setScrollLock() {
		DefaultCaret caret1 = (DefaultCaret) textObjectif.getCaret();
		caret1.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);

		DefaultCaret caret2 = (DefaultCaret) textContenu.getCaret();
		caret2.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
	}

	/**
	 * Definition des butons sauvegarder et reinitialiser
	 * 
	 */
	public void setBtnActions() {
		btnSauvegarder.addActionListener(new EcouteurModifier());

		btnReinitialiser.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					int id = Integer.valueOf(textIdFormation.getText());
					lireFormation(id);
				} catch (Exception ex) {

				}

			}
		});
	}

	/**
	 * Rempli la liste de themes et selectionne les themes lies à cette
	 * formation.
	 */
	public void setThemeList() {
		themeListModel = new DefaultListModel<Theme>();
		themeList = new JList<Theme>(themeListModel);
		themeList.setBorder(new EmptyBorder(5, 5, 5, 5));
		themeList.setMinimumSize(new Dimension(0, 50));
		themeList.setMaximumSize(new Dimension(0, 50));
		themeList.setVisibleRowCount(5);

		try {
			ThemeDAO themeDao = new ThemeDAO();
			List<Theme> themes = themeDao.lister();
			for (int i = 0; i < themes.size(); i++) {
				themeListModel.add(i, themes.get(i));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		themeList.setCellRenderer(new ThemeCellRenderer());

		themesScrollPanel.setViewportView(themeList);
	}

	public void setFormationListePanel(FormationListePanel formationListePanel) {
		this.formationListePanel = formationListePanel;
	}

	/**
	 * lit les donnees d'une formation à partir de son ID
	 * Met à jour les champs de saisie
	 * 
	 * @param id
	 */
	public void lireFormation(int id) {

		isModified(id);

		try {
			Formation f = FormationDAO.lireParId(id);

			if (f != null) {
				updateTextField(f);
			} else {
				System.out.println("L'ID " + id + " n'existe pas.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Contrôle si les champs de saisie modifie afin d'avertir l'utilisateur
	 * 
	 * @param newFormationId
	 */
	public void isModified(int newFormationId) {
		try {
			if (newFormationId != edtFormationId && edtFormationId != 0) {
				Formation f1 = setFormation();
				Formation f2 = FormationDAO.lireParId(edtFormationId);

				if (!f1.equals(f2)) {
					int result = JOptionPane.showConfirmDialog(this, "La formation selectionne est changee. Voulez-vous l'enregistrer?",
							"Enregistrer la formation", JOptionPane.YES_NO_OPTION);
					switch (result) {
						case JOptionPane.YES_OPTION:
							saveFormation();
							return;
						case JOptionPane.NO_OPTION:
							return;
						case JOptionPane.CLOSED_OPTION:
							return;
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public Formation setFormation() {
		String idText = textIdFormation.getText();
		int id = 0;
		if (idText.equals("")) {
			id = 0;
		} else {
			id = Integer.valueOf(idText);
		}
		String nom = textCode.getText();
		String prenom = textTitre.getText();

		String telephone = textObjectif.getText();
		String adresse = textContenu.getText();
		String codePostal = textCertification.getText();
		String ville = textPrerequis.getText();

		Formation f = new Formation(id, nom, prenom, telephone, adresse, codePostal, ville);
		return f;
	}

	class ThemeCellRenderer extends DefaultListCellRenderer {

		private static final long	serialVersionUID	= 1L;

		/* This is the only method defined by ListCellRenderer.  We just
		 * reconfigure the Jlabel each time we're called.
		 */
		public Component getListCellRendererComponent(JList list, Object value, // value
																				// to
																				// display
				int index, // cell index
				boolean iss, // is the cell selected
				boolean chf) // the list and the cell have the focus
		{
			/* The DefaultListCellRenderer class will take care of
			 * the JLabels text property, it's foreground and background
			 * colors, and so on.
			 */
			super.getListCellRendererComponent(list, ((Theme) value).getLibelle(), index, iss, chf);

			return this;
		}
	}

	class EcouteurModifier implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent ev) {

			saveFormation();

		}

	}

	/**
	 * Sauvegarder ou creer une formation
	 */
	public void saveFormation() {
		int idFormation = 0;
		try {
			idFormation = Integer.parseInt(textIdFormation.getText());
		} catch (Exception e) {

		}
		String code = textCode.getText();
		String titre = textTitre.getText();
		String objectif = textObjectif.getText();
		String contenu = textContenu.getText();
		String certification = textCertification.getText();
		String prerequis = textPrerequis.getText();

		Formation f = new Formation(code, titre, objectif, contenu, certification, prerequis);
		System.out.println(f);

		if (controlFormationFields(f)) {
			try {
				if (idFormation != 0) {
					f.setIdFormation(idFormation);
					FormationDAO.modifier(f);
				} else {
					FormationDAO.inserer(f);
					textIdFormation.setText("" + f.getIdFormation());
				}

				// supprimer tous
				FormationThemeDAO.supprimer(idFormation);
				// ajouter à nouveau
				for (Theme theme : themeList.getSelectedValuesList()) {
					System.out.println("sel" + theme.getId_theme());
					FormationThemeDAO.inserer(f, theme);
				}

				System.out.println("La formation a été modifiée.");
				formationListePanel.rechercheFormation("");
			} catch (SQLException e) {

				JOptionPane.showMessageDialog(FormationPanel.this, e.getMessage(), "Sauvegarder la formation", JOptionPane.INFORMATION_MESSAGE);
				e.printStackTrace();
			}

		} else {
			System.out.println("Code ou titre ne sont pas renseigne");
			JOptionPane.showMessageDialog(FormationPanel.this,
					"Vous devez remplir les champs de saisie : \nCode ou titre \n et choisir au moins un theme", "Sauvegarder la formation",
					JOptionPane.INFORMATION_MESSAGE);

		}
	}

	/**
	 * Met à jour les champs de saisie
	 * 
	 * @param f
	 */
	public void updateTextField(Formation f) {

		if (f.getIdFormation() == 0) {
			edtFormationId = 0;
			textIdFormation.setText("");
			themeList.clearSelection();
		} else {
			edtFormationId = f.getIdFormation();
			textIdFormation.setText("" + f.getIdFormation());

			try {

				ArrayList<Theme> selectedThemes = new ArrayList<Theme>();

				for (Theme theme : FormationThemeDAO.getFormationThemes(f)) {
					selectedThemes.add(theme);
				}

				int[] themes = new int[selectedThemes.size()];

				int j = 0;
				for (int i = 0; i < themeListModel.size(); i++) {
					if (selectedThemes.contains(themeListModel.get(i))) {
						themes[j++] = i;
					}
				}

				themeList.setSelectedIndices(themes);

			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		textCode.setText(f.getCode());
		textTitre.setText(f.getTitre());
		textObjectif.setText(f.getObjectif());
		textContenu.setText(f.getContenu());
		textCertification.setText(f.getCertification());
		textPrerequis.setText(f.getPrerequis());

	}

	/**
	 * Met le curseur dans textTitre
	 */
	public void focus() {
		textTitre.requestFocusInWindow();
	}

	/**
	 * Contrôle tous les champs requis pour sauvegarder ou creer une formation
	 * 
	 * @param f
	 * @return
	 */
	public boolean controlFormationFields(Formation f) {

		if (f == null)
			return false;
		if (f.getTitre().isEmpty()) {
			textTitre.requestFocusInWindow();
			return false;
		}
		if (f.getCode().isEmpty()) {
			textCode.requestFocusInWindow();
			return false;
		}

		if (themeList.getSelectedIndices().length == 0) {
			return false;
		}

		return true;

	}

	class JTextAreaWithScroll extends JTextArea {

		private static final long	serialVersionUID	= 1L;
		private JScrollPane			scrollPane;

		public JTextAreaWithScroll(int vsbPolicy, int hsbPolicy) {
			this.setLineWrap(true);
			scrollPane = new JScrollPane(this, vsbPolicy, hsbPolicy);
		}

		public JScrollPane getScrollPane() {
			return scrollPane;
		}
	}
}
